var http = require('http');
var cluster = require('cluster');
var utils = require('./utils');
var conversion_handler = require('./conversion_handler');
var download_handler = require('./download_handler');

function start() {
  if (cluster.isMaster) {
    for (var i = 0; i < 10; i++) {
      cluster.fork();
    }
    
    cluster.on('death', function(worker) {
      console.log('Thread ' + worker.pid + ' died');
    });
  } else {
    http.createServer(function (request, response) {
      var prop = utils.get_file_prop_from_url(request.url);
      var converted_file = conversion_handler.convert(prop['name'], prop['new_type']);
      download_handler.send(request, response, converted_file);
    }).listen(8124);
  }
  
  console.log('Server running at http://127.0.0.1:8124/');
}

exports.start = start;
